package org.club.Service.impl;

import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.club.Service.FileOssService;
import org.club.Service.UserService;
import org.club.common.model.dto.*;
import org.club.common.model.entity.AnnouncementWithReadStatus;
import org.club.common.model.entity.ClubActivityInfo;
import org.club.common.model.entity.Clubs;
import org.club.common.model.vo.*;
import org.club.mapper.ActivityMapper;
import org.club.mapper.UserMapper;
import org.club.common.model.entity.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FileOssService fileOssService;
    @Autowired
    private ActivityMapper activityMapper;

    @Override
    public List<ClubInfoVO> selectClubsList(ClubInfoDto clubInfoDto, Long userId) {
        PageHelper.startPage(clubInfoDto.getPageNum(), clubInfoDto.getPageSize());
        List<ClubInfoVO> clubInfoVOList = userMapper.selectClubsList(clubInfoDto.getStatus(), clubInfoDto.getName(), userId);
        if (clubInfoVOList == null) {
            throw new BusinessException(400, "查询社团列表失败");
        }
        return clubInfoVOList;
    }

    @Override
    public Integer selectClubsListTotal() {
        return userMapper.selectClubsListTotal();
    }

    //加入社团
    @Override
    public void joinClub(Long clubId, String username) {
        if (clubId == null || username == null) {
            throw new BusinessException(400, "参数错误");
        }
        //查询该用户的ID
        Long userId = userMapper.selectUserId(username);
        //验证该用户是否存在以及是否加入其他社团或者是其他社团的管理员
        if (userMapper.selectUser(username) != 1) {
            throw new BusinessException(400, "该用户不存在");
        }
        if (userMapper.selectClubsUser(clubId, userId) != 0) {
            throw new BusinessException(400, "该用户已加入该社团");
        }
        if (userMapper.selectclub_admins(username) != 0) {
            throw new BusinessException(400, "该用户是其他社团的管理员,暂不可加入其他社团");
        }
        try {
            //验证该用户的状态
            Integer s =userMapper.selectClubsUserStatus(userId,clubId);
            if (s==1){
                //存在则更新
                Integer o =userMapper.UpdateClubsUsersttus(clubId,userId);
                if (o != 1){
                    throw new BusinessException(400, "加入社团失败");
                }
            }else {
                //不存在则插入
                Integer i = userMapper.joinClub(clubId, userId);
                log.info("加入社团成功{}", i);
                if (i != 1) {
                    throw new BusinessException(400, "加入社团失败");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(400, "加入社团失败");
        }

    }

    //查询加入的社团
    @Override
    public List<ClubInfoVO> selectjoinClubsList(Long userId) {
        if (userId == null) {
            throw new BusinessException(400, "参数错误");
        }
        //查询用户加入的社团ID列表
        List<Long> clubIdList = userMapper.selectClubsIdLsit(userId);
        if (clubIdList.isEmpty()) {
            throw new BusinessException(400, "该用户暂未加入任何社团");
        }
        //通过社团ID列表查询社团信息
        List<ClubInfoVO> clubInfoVOList = userMapper.selectjoinClubsList(clubIdList);
        return clubInfoVOList;
    }

    @Override
    public void quitClub(Long clubId, Long userId) {
        if (clubId == null || userId == null) {
            throw new BusinessException(400, "参数错误");
        }
        Integer i = userMapper.quitClub(clubId, userId);
        if (i != 1) {
            throw new BusinessException(400, "退出社团失败");
        }
        log.info("退出社团成功{}", i);
    }

    @Override
    public List<ActivitiesVO> selectActivities(Long clubId) {
        if (clubId == null) {
            throw new BusinessException(400, "参数错误");
        }
        List<ActivitiesVO> activitiesVOList = userMapper.selectActivities(clubId);
        if (activitiesVOList == null) {
            throw new BusinessException(400, "当前社团暂无已发布的活动");
        }
        return activitiesVOList;
    }

    //学生报名活动
    @Override
    public void signUpActivity(Long activityId, Long userId) {
        if (activityId == null || userId == null) {
            throw new BusinessException(400, "参数错误");
        }
        //检查改用户是否已经报名改活动
        if (userMapper.selectUserSignUpActivitiesCount(userId,activityId) != 0) {
            throw new BusinessException(400, "该用户已经报名该活动");
        }
        try {
            Integer i = userMapper.signUpActivity(activityId, userId);
            log.info("报名成功{}", i);
            if (i != 1) {
                throw new BusinessException(400, "报名失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(400, "报名失败" + e.getMessage());
        }

    }

    @Override
    public List<ActivitiesNumberApplicantsVO> selectAllActivities(ActivityQueryDTO activityQueryDTO) {
        Boolean isVals = false;
        if (activityQueryDTO.getEndTime() != null && activityQueryDTO.getStartTime() != null) {
            isVals = true;
        }
        if (isVals && activityQueryDTO.getStartTime().isAfter(activityQueryDTO.getEndTime())) {
            throw new BusinessException(400, "开始时间不能晚于结束时间");
        }
        try {
            List<ActivitiesNumberApplicantsVO> activitiesVO = userMapper.selectActivitiesList(activityQueryDTO);
            log.info("查询活动列表：{}", activitiesVO);
            if (activitiesVO == null) {
                throw new BusinessException(400, "暂无活动");
            }
            return activitiesVO;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(400, "查询失败" + e.getMessage());
        }

    }

    @Override
    public List<Registration_InformationVO> selectUserSignUpActivities(Long userId, Integer status, String keyword) {
        if (userId == null) {
            throw new BusinessException(400, "参数错误");
        }
        List<Registration_InformationVO> activitiesVOList = userMapper.selectUserSignUpActivities(
                userId, status, keyword);
        return activitiesVOList;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void CreateCommunity(ClubsDto clubsDto, Long user_id, MultipartFile file) {
        if (clubsDto == null || user_id == null || user_id == 0 || file.isEmpty()) {
            throw new BusinessException(400, "参数为空");
        }
        //验证该用户是否加入了其他社团或者是其他社团的管理员
        Integer ii = userMapper.selectclub_admins(String.valueOf(user_id));
        if (ii != 0) {
            throw new BusinessException(400, "该用户已经提交过创建社团的申请,暂不可创建社团");
        }
        Integer q = userMapper.selectclub_members(user_id);
        if (q != 0) {
            throw new BusinessException(400, "该用户已加入其他社团,请先退出加入的社团再进行创建");
        }
        String FileUrl = "";
        try {
            //上传图片获取图片路径
            FileUrl = fileOssService.uploadToOss(file);
            clubsDto.setCoverUrl(FileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            fileOssService.deleteFileFromOss(FileUrl);
            throw new BusinessException(400, "上传图片失败");
        }
        log.info("上传图片成功{}", clubsDto);
        Integer i = userMapper.CreateCommunity(clubsDto);
        Integer p = userMapper.Insertionclub_admins(clubsDto.getId(), user_id);
        if (i == null || i == 0 || p == null || p == 0) {
            throw new BusinessException(400, "创建失败");
        }
    }

    @Override
    public Clubs selectClubsProcess(Long userId) {
        if (userId == null || userId == 0) {
            throw new BusinessException(400, "参数为空");
        }
        //将Long转为String
        Integer i = userMapper.selectclub_admins(String.valueOf(userId));
        if (i<1) {
            throw new BusinessException(400, "该用户暂未有提交的社团创建的申请");
        }
        //查询该用户的社团ID
        Clubs clubs = userMapper.selectClubs(userId);
        if (clubs == null){
            throw new BusinessException(400, "该用户暂未有提交的社团创建的申请");
        }
        return clubs;
    }

    @Override
    public List<AnnouncementWithReadStatus> selectSystemAnnouncements(AnnouncementQueryDTO announcementQueryDTO) {
        if (announcementQueryDTO.getUserId() == null) {
            throw new BusinessException(400, "参数错误");
        }
        List<AnnouncementWithReadStatus> announcements = userMapper.selectSystemAnnouncements(announcementQueryDTO);
        if (announcements == null) {
            throw new BusinessException(400, "暂无系统公告");
        }
        return announcements;
    }

    //显示未读数量
    @Override
    public Integer selectUnreadCount(Long userId) {
        if (userId == null) {
            throw new BusinessException(400, "参数错误");
        }
        return userMapper.selectUnreadCount(userId);
    }

    //修改系统公告已读状态
    @Override
    public void updateAnnouncementReadStatus(Long announcement_id) {
        if (announcement_id == null) {
            throw new BusinessException(400, "参数错误");
        }
        Integer i = userMapper.updateAnnouncementReadStatus(announcement_id);
        if (i == 0) {
            throw new BusinessException(400, "修改失败");
        }
    }

    @Override
    public ClubsDetailVO selectClubsDetail(Long clubId) {
        if (clubId == null){
            throw new BusinessException(400, "参数错误");
        }
        try {
            ClubsDetailVO clubsDetailVO = userMapper.selectClubsDetail(clubId);
            return clubsDetailVO;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(400, "查询失败");
        }

    }
//查询社团成员和活动
    @Override
    public List<ClubActivityInfo> selectClubsMembers(Long clubId) {
        if (clubId == null) {
            throw new BusinessException(400, "参数错误");
        }
        try {
            List<ClubActivityInfo> clubActivityInfo = userMapper.selectClubsMembers(clubId);
            if (clubActivityInfo == null){
                throw new BusinessException(400, "暂无社团成员和活动");
            }
            return clubActivityInfo;
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException(400, "查询失败");
        }
    }

    @Override
    public UserVo updatePersonalInfos(UpdatePersonalInfoRequestDto updatePersonalInfoRequestDto, MultipartFile file) {
        if (updatePersonalInfoRequestDto.getUserId()==null){
            throw new BusinessException(400, "用户ID不能为空");
        }
        //检查该用户是否存在
        Integer i = activityMapper.selectUser(updatePersonalInfoRequestDto.getUserId());
        if (i==0){
            throw new BusinessException(400, "用户不存在");
        }
        try {
            if (file!=null){
                //上传图片到OSS
                String s = fileOssService.uploadToOss(file);
                if (s!=null){
                    updatePersonalInfoRequestDto.setNewAvatarUrl(s);
                }
            }

            log.info("更新个人信息，用户ID: {}, 真实姓名: {}, 电话: {}, 邮箱: {}, 新头像地址: {}", updatePersonalInfoRequestDto.getUserId(), updatePersonalInfoRequestDto.getRealName(), updatePersonalInfoRequestDto.getPhone(), updatePersonalInfoRequestDto.getEmail(), updatePersonalInfoRequestDto.getNewAvatarUrl());
            Integer n =activityMapper.updatePersonalInfo(updatePersonalInfoRequestDto);
            if (n<=0){
                throw new BusinessException(500, "更新个人信息失败");
            }
            if (updatePersonalInfoRequestDto.getNewAvatarUrl()!=null){
                //最后删除OSS原始图片
                Boolean b = fileOssService.deleteFileFromOss(updatePersonalInfoRequestDto.getOriginalAvatarUrl());
                log.info("删除OSS原始图片，原始图片地址: {}", b);
            }
            //返回更新后的用户信息
            UserVo userVo = activityMapper.selectUserInfo(updatePersonalInfoRequestDto.getUserId());
            return userVo;
        }catch (Exception e){
            e.printStackTrace();
            fileOssService.deleteFileFromOss(updatePersonalInfoRequestDto.getNewAvatarUrl());
            throw new BusinessException(500, "更新个人信息失败");
        }
    }

    @Override
    public List<ActivityCommentVO> getComments(Long activityId) {
        // 1. 查询所有评论
        List<ActivityCommentVO> allComments = activityMapper.getComments(activityId);

        // 2. 构建id->评论的Map
        Map<Integer, ActivityCommentVO> idMap = new HashMap<>();
        for (ActivityCommentVO comment : allComments) {
            comment.setReplies(new ArrayList<>());
            idMap.put(comment.getId(), comment);
        }

        // 3. 组装树结构
        List<ActivityCommentVO> rootComments = new ArrayList<>();
        for (ActivityCommentVO comment : allComments) {
            if (comment.getParentId() == null) {
                rootComments.add(comment);
            } else {
                ActivityCommentVO parent = idMap.get(comment.getParentId());
                if (parent != null) {
                    parent.getReplies().add(comment);
                }
            }
        }
        return rootComments;
    }

    @Override
    public void createComment(ActivityCommentDTO commentDTO) {
        if (commentDTO == null) {
            throw new BusinessException(400, "评论信息不能为空");
        }
        if (commentDTO.getReplierId() == null) {
            throw new BusinessException(400, "评论者ID不能为空");
        }
        Integer i = activityMapper.createComment(commentDTO);
        log.info("创建评论成功，活动ID: {}, 用户ID: {}, 内容: {}", commentDTO.getActivityId(), commentDTO.getReplierId(), commentDTO.getContent());
        if (i <= 0) {
            throw new BusinessException(500, "创建评论失败");
        }
    }

    @Override
    public Long getCommentAuthorId(Long activityId) {
        if (activityId == null){
            throw new BusinessException(400, "活动ID错误");
        }
        Long authorId = activityMapper.getCommentAuthorId(activityId);
        return authorId;
    }

}
